<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑气泡' : '新增气泡'"
    width="550px"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    class="tech-dialog bubble-form-dialog"
    @closed="handleDialogClosed"
  >
    <div class="dialog-content">
      <dv-border-box-8 class="form-container">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
          class="tech-form"
          v-loading="loading"
          element-loading-text="数据加载中..."
          element-loading-background="rgba(0, 20, 40, 0.8)"
        >
          <!-- 标签 -->
          <el-form-item label="标签" prop="tag">
            <el-input 
              v-model="formData.tag" 
              placeholder="请输入标签文本" 
              class="tech-input"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <!-- 行业类型 -->
          <el-form-item label="行业类型" prop="mapNode">
            <el-input 
              v-model="formData.mapNode" 
              placeholder="请输入地图节点名称" 
              class="tech-input"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <!-- 气泡类型 -->
          <el-form-item label="气泡类型" prop="type">
            <el-select 
              v-model="formData.type" 
              placeholder="请选择节点类型"
              class="tech-select"
            >
              <el-option label="热门行业" value="hot-industry" />
              <el-option label="普通行业" value="common-industry" />
              <el-option label="新兴行业" value="emerging-industry" />
            </el-select>
          </el-form-item>

          <!-- 节点大小 -->
          <el-form-item label="节点大小" prop="size">
            <div class="slider-input-group">
              <el-slider 
                v-model="formData.size" 
                :min="50" 
                :max="300" 
                :step="1"
                class="tech-slider"
              />
              <el-input-number 
                v-model="formData.size" 
                :min="50" 
                :max="300" 
                :step="1"
                class="tech-input-number"
                controls-position="right"
              />
            </div>
          </el-form-item>

          <!-- 位置坐标 -->
          <el-form-item label="位置坐标" class="position-form-item">
            <div class="position-inputs">
              <div class="position-sub-item">
                <div class="position-label">X:</div>
                <div class="slider-input-group">
                  <el-slider 
                    v-model="formData.position.x" 
                    :min="0" 
                    :max="1000" 
                    :step="1"
                    class="tech-slider"
                  />
                  <el-input-number 
                    v-model="formData.position.x" 
                    :min="0" 
                    :max="1000" 
                    :step="1"
                    class="tech-input-number"
                    controls-position="right"
                  />
                </div>
              </div>
              <div class="position-sub-item">
                <div class="position-label">Y:</div>
                <div class="slider-input-group">
                  <el-slider 
                    v-model="formData.position.y" 
                    :min="0" 
                    :max="1000" 
                    :step="1"
                    class="tech-slider"
                  />
                  <el-input-number 
                    v-model="formData.position.y" 
                    :min="0" 
                    :max="1000" 
                    :step="1"
                    class="tech-input-number"
                    controls-position="right"
                  />
                </div>
              </div>
            </div>
          </el-form-item>

          <!-- 动画持续时间 -->
          <el-form-item label="动画时长" prop="animationDuration">
            <div class="slider-input-group">
              <el-slider 
                v-model="formData.animationDuration" 
                :min="0.1" 
                :max="10" 
                :step="0.1"
                class="tech-slider"
              />
              <el-input-number 
                v-model="formData.animationDuration" 
                :min="0.1" 
                :max="10" 
                :step="0.1"
                :precision="1"
                class="tech-input-number"
                controls-position="right"
              />
              <span class="unit-text">秒</span>
            </div>
          </el-form-item>

          <!-- 渐变色 -->
          <el-form-item label="渐变色" class="gradient-form-item">
            <div class="gradient-inputs">
              <div class="gradient-sub-item">
                <div class="gradient-label">起始色:</div>
                <div class="color-picker-group">
                  <el-color-picker 
                    v-model="startColorTemp" 
                    class="tech-color-picker"
                    @change="handleStartColorChange"
                  />
                  <el-input 
                    v-model="formData.gradient.start" 
                    placeholder="#RRGGBB" 
                    class="tech-input color-input"
                  />
                </div>
              </div>
              <div class="gradient-sub-item">
                <div class="gradient-label">结束色:</div>
                <div class="color-picker-group">
                  <el-color-picker 
                    v-model="endColorTemp" 
                    class="tech-color-picker"
                    @change="handleEndColorChange"
                  />
                  <el-input 
                    v-model="formData.gradient.end" 
                    placeholder="#RRGGBB" 
                    class="tech-input color-input"
                  />
                </div>
              </div>
            </div>
          <div class="gradient-preview">
            <div class="gradient-preview-label">预览效果：</div>
            <div 
              class="gradient-preview-box" 
              :style="{
                background: `linear-gradient(to right, ${formData.gradient.start || '#000000'}, ${formData.gradient.end || '#000000'})`
              }"
            ></div>
          </div>
          </el-form-item>

          <!-- 启用状态 -->
          <el-form-item label="启用状态">
            <el-switch
              v-model="formData.enable"
              active-text="开启"
              inactive-text="关闭"
              class="tech-switch"
              active-color="#00c0ff"
              inactive-color="#666"
            />
            <div class="switch-tip">控制该气泡是否在前端展示</div>
          </el-form-item>
        </el-form>
      </dv-border-box-8>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button 
          @click="dialogVisible = false" 
          class="tech-button"
        >
          取消
        </el-button>
        <el-button 
          type="primary" 
          @click="submitForm" 
          :loading="submitting"
          class="tech-button tech-button--primary"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { app, ensureLogin } from '../../utils/cloudbase'

// 颜色转换为十六进制
function colorToHex(color) {
  // 如果已经是十六进制格式，直接返回
  if (typeof color === 'string' && color.startsWith('#')) {
    return color;
  }
  
  // 创建一个临时元素来计算RGB值
  const div = document.createElement('div');
  div.style.color = color;
  document.body.appendChild(div);
  
  // 获取计算后的样式
  const computedColor = window.getComputedStyle(div).color;
  document.body.removeChild(div);
  
  // 解析RGB值
  const rgb = computedColor.match(/\d+/g);
  if (!rgb || rgb.length < 3) {
    return '#000000';
  }
  
  // 转换为十六进制
  const hex = '#' + 
    parseInt(rgb[0]).toString(16).padStart(2, '0') +
    parseInt(rgb[1]).toString(16).padStart(2, '0') +
    parseInt(rgb[2]).toString(16).padStart(2, '0');
  
  return hex;
}

export default {
  name: 'BubbleFormDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    bubbleData: {
      type: Object,
      default: () => null
    }
  },
  emits: ['update:visible', 'refresh'],
  setup(props, { emit }) {
    // 表单引用
    const formRef = ref(null)
    
    // 对话框状态
    const dialogVisible = ref(false)
    const loading = ref(false)
    const submitting = ref(false)
    
    // 表单数据
    const formData = reactive({
      _id: '',
      id: '',
      tag: '',
      mapNode: '',
      type: 'common-industry',
      size: 100,
      position: {
        x: 500,
        y: 500
      },
      animationDuration: 2.0,
      gradient: {
        start: '#1089ff',
        end: '#00bcd4'
      },
      enable: true
    })
    
    // 临时颜色值，用于颜色选择器
    const startColorTemp = ref(formData.gradient.start)
    const endColorTemp = ref(formData.gradient.end)
    
    // 处理起始颜色变化
    const handleStartColorChange = (color) => {
      formData.gradient.start = colorToHex(color)
    }
    
    // 处理结束颜色变化
    const handleEndColorChange = (color) => {
      formData.gradient.end = colorToHex(color)
    }
    
    // 表单验证规则
    const rules = {
      tag: [
        { required: true, message: '请输入标签文本', trigger: 'blur' },
        { min: 1, max: 30, message: '标签长度应为1-30个字符', trigger: 'blur' }
      ],
      mapNode: [
        { required: true, message: '请输入地图节点名称', trigger: 'blur' },
        { min: 1, max: 50, message: '节点名称长度应为1-50个字符', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择节点类型', trigger: 'change' }
      ],
      size: [
        { required: true, message: '请设置节点大小', trigger: 'change' },
        { type: 'number', min: 50, max: 300, message: '节点大小应在50-300之间', trigger: 'change' }
      ],
      'position.x': [
        { required: true, message: '请设置X坐标', trigger: 'change' },
        { type: 'number', min: 0, max: 1000, message: 'X坐标应在0-1000之间', trigger: 'change' }
      ],
      'position.y': [
        { required: true, message: '请设置Y坐标', trigger: 'change' },
        { type: 'number', min: 0, max: 1000, message: 'Y坐标应在0-1000之间', trigger: 'change' }
      ],
      animationDuration: [
        { required: true, message: '请设置动画持续时间', trigger: 'change' },
        { type: 'number', min: 0.1, max: 10, message: '动画持续时间应在0.1-10秒之间', trigger: 'change' }
      ],
      'gradient.start': [
        { required: true, message: '请设置渐变起始色', trigger: 'change' },
        { pattern: /^#[0-9A-Fa-f]{6}$/, message: '颜色格式应为#RRGGBB', trigger: 'change' }
      ],
      'gradient.end': [
        { required: true, message: '请设置渐变结束色', trigger: 'change' },
        { pattern: /^#[0-9A-Fa-f]{6}$/, message: '颜色格式应为#RRGGBB', trigger: 'change' }
      ]
    }
    
    // 计算属性：是否为编辑模式
    const isEdit = computed(() => {
      return !!formData._id
    })
    
    // 监听visible属性变化
    watch(() => props.visible, (val) => {
      dialogVisible.value = val
      if (val) {
        resetForm()
        if (props.bubbleData) {
          // 编辑模式，填充表单数据
          fillFormData(props.bubbleData)
        }
      }
    })
    
    // 监听dialogVisible变化，同步到父组件
    watch(() => dialogVisible.value, (val) => {
      emit('update:visible', val)
    })
    
    // 重置表单
    const resetForm = () => {
      formData._id = ''
      formData.id = ''
      formData.tag = ''
      formData.mapNode = ''
      formData.type = 'common-industry'
      formData.size = 100
      formData.position.x = 500
      formData.position.y = 500
      formData.animationDuration = 2.0
      formData.gradient.start = '#1089ff'
      formData.gradient.end = '#00bcd4'
      formData.enable = true
      
      // 重置表单验证
      nextTick(() => {
        formRef.value?.clearValidate()
      })
    }
    
    // 填充表单数据
    const fillFormData = (data) => {
      formData._id = data._id || ''
      formData.id = data.id || ''
      formData.tag = data.tag || ''
      formData.mapNode = data.mapNode || ''
      formData.type = data.type || 'common-industry'
      formData.size = data.size || 100
      formData.position.x = data.position?.x || 500
      formData.position.y = data.position?.y || 500
      formData.animationDuration = data.animationDuration || 2.0
      formData.gradient.start = data.gradient?.start || '#1089ff'
      formData.gradient.end = data.gradient?.end || '#00bcd4'
      formData.enable = data.enable !== false // 默认为true
      
      // 更新临时颜色值
      startColorTemp.value = formData.gradient.start
      endColorTemp.value = formData.gradient.end
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid, fields) => {
        if (!valid) {
          console.error('表单验证失败:', fields)
          return
        }
        
        submitting.value = true
        try {
          await ensureLogin()
          
          // 准备提交数据
          const submitData = {
            tag: formData.tag,
            mapNode: formData.mapNode,
            type: formData.type,
            size: formData.size,
            position: {
              x: formData.position.x,
              y: formData.position.y
            },
            animationDuration: formData.animationDuration,
            gradient: {
              start: formData.gradient.start,
              end: formData.gradient.end
            },
            enable: formData.enable
          }
          
          // 编辑模式需要传入ID
          if (isEdit.value) {
            submitData._id = formData._id
            submitData.id = formData.id
          }
          
          // 调用云函数
          const res = await app.callFunction({
            name: 'admin-bubble-tags-crud',
            data: {
              action: isEdit.value ? 'update' : 'create',
              data: submitData
            }
          })
          
          const result = res.result || {}
          
          if (result.code === 0) {
            ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
            dialogVisible.value = false
            emit('refresh') // 通知父组件刷新数据
          } else {
            ElMessage.error(result.message || (isEdit.value ? '更新失败' : '添加失败'))
          }
        } catch (error) {
          console.error('提交表单出错:', error)
          ElMessage.error('提交表单出错: ' + error.message)
        } finally {
          submitting.value = false
        }
      })
    }
    
    // 对话框关闭处理
    const handleDialogClosed = () => {
      resetForm()
    }
    
    return {
      formRef,
      dialogVisible,
      loading,
      submitting,
      formData,
      rules,
      isEdit,
      startColorTemp,
      endColorTemp,
      handleStartColorChange,
      handleEndColorChange,
      resetForm,
      fillFormData,
      submitForm,
      handleDialogClosed
    }
  }
}
</script>

<style scoped>
.dialog-content {
  padding: 0;
}

.form-container {
  padding: 15px;
  background-color: rgba(0, 19, 47, 0.8);
}

.tech-form {
  max-width: 100%;
}

.tech-input,
.tech-select,
.tech-input-number {
  width: 100%;
  background-color: rgba(0, 20, 40, 0.7);
  border-color: rgba(0, 192, 255, 0.3);
  color: #ffffff;
}

.tech-input:focus,
.tech-select:focus,
.tech-input-number:focus {
  border-color: rgba(0, 192, 255, 0.8);
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.3);
}

.tech-input input,
.tech-select input,
.tech-input-number input {
  background-color: transparent;
  color: #ffffff;
}

.tech-slider {
  margin-right: 10px;
  flex: 1;
}

.slider-input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.tech-input-number {
  width: 100px;
  flex-shrink: 0;
}

.unit-text {
  margin-left: 5px;
  color: rgba(0, 192, 255, 0.8);
  flex-shrink: 0;
}

.position-inputs,
.gradient-inputs {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
}

.position-sub-item,
.gradient-sub-item {
  width: 100%;
  margin-bottom: 10px;
}

.position-label,
.gradient-label {
  color: rgba(0, 192, 255, 0.8);
  margin-bottom: 5px;
  font-size: 14px;
}

.color-picker-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.tech-color-picker {
  margin-right: 10px;
  flex-shrink: 0;
}

.color-input {
  flex: 1;
}

.gradient-preview {
  margin-top: 15px;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.gradient-preview-label {
  margin-bottom: 8px;
  color: rgba(0, 192, 255, 0.8);
}

.gradient-preview-box {
  width: 100%;
  height: 40px;
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.3);
  position: relative;
  overflow: hidden;
}

.gradient-preview-box::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent 65%, rgba(255, 255, 255, 0.2) 70%, transparent 75%);
  background-size: 200% 200%;
  animation: gradient-shine 2s infinite;
}

@keyframes gradient-shine {
  0% {
    background-position: 0% 0%;
  }
  100% {
    background-position: 200% 200%;
  }
}

.tech-switch {
  --el-switch-on-color: #00c0ff;
  --el-switch-off-color: rgba(0, 30, 60, 0.6);
}

.switch-tip {
  font-size: 12px;
  color: rgba(0, 192, 255, 0.8);
  margin-top: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 10px;
}

:deep(.el-dialog) {
  background-color: rgba(0, 19, 47, 0.9);
  border: 1px solid rgba(0, 192, 255, 0.5);
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3);
  border-radius: 4px;
  backdrop-filter: blur(5px);
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: rgba(0, 30, 60, 0.8);
  border-bottom: 1px solid rgba(0, 192, 255, 0.3);
  padding: 15px 20px;
}

:deep(.el-dialog__title) {
  color: #00c0ff;
  font-size: 18px;
  text-shadow: 0 0 5px rgba(0, 192, 255, 0.5);
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: rgba(0, 192, 255, 0.8);
}

:deep(.el-dialog__body) {
  padding: 15px;
  color: #ffffff;
  overflow: hidden;
}

.tech-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid rgba(0, 192, 255, 0.3);
  padding: 15px 20px;
}

:deep(.el-form-item__label) {
  color: rgba(0, 192, 255, 0.8);
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-slider__runway) {
  background-color: rgba(0, 30, 60, 0.6);
}

:deep(.el-slider__bar) {
  background-color: rgba(0, 192, 255, 0.8);
}

:deep(.el-slider__button) {
  border-color: rgba(0, 192, 255, 0.8);
  background-color: #00c0ff;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  background-color: rgba(0, 20, 40, 0.7);
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.3) inset;
}

:deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.5) inset;
}

:deep(.el-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.8) inset;
}

:deep(.el-select__popper) {
  background-color: rgba(0, 20, 40, 0.95) !important;
  border: 1px solid rgba(0, 192, 255, 0.3) !important;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.2) !important;
}

:deep(.el-select-dropdown) {
  background-color: rgba(0, 20, 40, 0.7) !important;
  border: 1px solid rgba(0, 192, 255, 0.3) !important;
}

:deep(.el-select-dropdown__item) {
  color: #ffffff;
  background-color: rgba(0, 20, 40, 0.7);
}

:deep(.el-select-dropdown__item.hover),
:deep(.el-select-dropdown__item:hover) {
  background-color: rgba(0, 192, 255, 0.2);
}

:deep(.el-select-dropdown__item.selected) {
  color: #00c0ff;
  background-color: rgba(0, 192, 255, 0.1);
}

:deep(.el-input__wrapper),
:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  background-color: rgba(0, 20, 40, 0.7);
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.3) inset;
}

:deep(.el-input__wrapper:hover),
:deep(.el-input-number__decrease:hover),
:deep(.el-input-number__increase:hover) {
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.5) inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.8) inset;
}

:deep(.el-input__inner) {
  color: #ffffff;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  color: rgba(0, 192, 255, 0.8);
  border-color: rgba(0, 192, 255, 0.3);
}

:deep(.el-input-number__decrease:hover),
:deep(.el-input-number__increase:hover) {
  color: #00c0ff;
  border-color: rgba(0, 192, 255, 0.5);
}

:deep(.el-input-number .el-input__inner) {
  -webkit-appearance: none;
  background-color: rgba(0, 20, 40, 0.7);
  color: #ffffff;
}
</style>